import { OPFetch } from '@ones-op/fetch'
import { exec, select, count } from '@ones-op/node-database'
import { Logger } from '@ones-op/node-logger'
import type { PluginRequest, PluginResponse } from '@ones-op/node-types'

// 考题 1-6 插件后端初始化创建"email_id_map"数据表
export async function addData(request: PluginRequest) {
  const body = request.body as any
  if (body.is_truncate === false) {
    try {
      await exec('delete', `delete from  email_id_map;`)
    } catch (error) {
      Logger.info('ERROR: ', error)
    }
  } else {
    // 随机的8位字符串
    const str = Math.random().toString(36).substring(2, 8)
    try {
      await exec('insert', `INSERT INTO email_id_map VALUES ("${str}");`)
    } catch (error) {
      Logger.info('ERROR: ', error)
    }
  }

  const result = await count('select count(*) from email_id_map;')
  return {
    body: {
      data: result,
    },
  }
}
